﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using blackhouse.JavaScript.JQuery;

namespace blackhouse.Web.Controls.Validators {
    public class RequiredFieldValidator :BaseValidator {

        #region Fields

        private WebControl _ctrlToValid;

        #endregion

        #region Properties

        protected WebControl CtrlToValidate {
            get {
                if (this._ctrlToValid == null)
                    this._ctrlToValid = this.FindControl(this.ControlToValidate) as WebControl;
                return this._ctrlToValid;
            }
        }

        #endregion
        
        protected override void Render(HtmlTextWriter writer) {
            //base.Render(writer);
        }

        protected override bool EvaluateIsValid() {
            string controlValidationValue = base.GetControlValidationValue(base.ControlToValidate);
            return ((controlValidationValue == null) || !controlValidationValue.Trim().Equals(string.Empty));

        }

        protected override void OnLoad(EventArgs e) {
            base.OnLoad(e);
            DefineValidator.LoadScript();
            this.CtrlToValidate.PreRender += CtrlToValidate_PreRender;
        }

        void CtrlToValidate_PreRender(object sender, EventArgs e) {
            WebControl ctrl = sender as WebControl;
            DefineValidator dv = new DefineValidator(ctrl, "required");
            dv.AddValidator();
            if (!string.IsNullOrEmpty(this.ErrorMessage))
                dv.AddMessage(this.ErrorMessage);
            this.CtrlToValidate.PreRender -= CtrlToValidate_PreRender;
        }

    }
}